package com.hup.utils.io.batch;

/**
 * @author hugan
 * @date 2020/1/22
 */
public class BatExecException extends RuntimeException {

    public final String cmd;

    /**
     * @param baseBatch nullable
     */
    protected BatExecException(String cmd, Exception cause, BaseBatch baseBatch) {
        super(buildMessage(cmd, cause, baseBatch), cause);
        this.cmd = cmd;
        //从新定义trace
        StackTraceElement[] causeTrace = cause.getStackTrace();
        StackTraceElement[] reset = new StackTraceElement[causeTrace.length + 1];
        reset[0] = getStackTrace()[0];
        System.arraycopy(causeTrace, 0, reset, 1, causeTrace.length);
        setStackTrace(reset);
    }

    private static String buildMessage(String cmd, Exception cause, BaseBatch baseBatch) {
        StringBuilder sb = new StringBuilder();
        if (baseBatch != null) {
            sb.append(baseBatch.desc()).append("错误,");
        }
        if (cause.getMessage().contains("系统找不到指定的文件")) {
            sb.append("命令不存在:[").append(cmd).append("]");
        } else {
            if (baseBatch == null) sb.append("命令执行错误:[").append(cmd).append(']');
            sb.append(cause.getMessage());
        }
        return sb.toString();
    }

}
